<script setup lang="ts">
import { fontSizeRem } from '@/utils/utils'
import { isSuccess } from '@/views/cockpit/common'
import Chat from '@/views/cockpit/components/chat.vue'
import * as api from '@/views/cockpit/dashboard/api'
import { getOrgAllInfo } from '@/views/cockpit/dashboard/api'
import { series, tooltip, windowResize, xAxis, yAxis } from '@/views/common'
import type { ECharts } from 'echarts'
import * as echarts from 'echarts'
import moment from 'moment'
import { onMounted, onUnmounted, ref } from 'vue'
// 考核管理
let glChat: ECharts
const glLineX = ref<string[]>([])
const glLineY = ref<number[]>([])
const initGlChat = () => {
  api.khRequest().then((res) => {
    if (isSuccess(res)) {
      let data = res.data.data || []
      data = data.filter((t) => t.companyName)
      data =
        data.filter((t) => {
          return !(t.sumScore == undefined || t.sumScore == null)
        }) || []
      glLineX.value = data.map((t) => t.companyName) || []
      glLineY.value = data.map((t) => t.sumScore) || []
    } else {
      glLineX.value = []
      glLineY.value = []
    }
  })
}
// 科研预算
const ysValue = ref<string[]>([])
const ysOptions = ref<Record<string, string>[]>([])
const ysEl = ref<HTMLDivElement>()
let ysChat: ECharts
const initYsChat = async () => {
  const data = await getOrgAllInfo()
  if (isSuccess(data)) {
    const options = data?.data?.data || []
    ysOptions.value = options
    if (options.length) {
      const arr: string[] = []
      const oneOptions = options[0]
      const reduceArr = (data: Record<string, any>) => {
        arr.push(data.id)
        if (data.children?.length) {
          reduceArr(data.children[0])
        }
      }
      reduceArr(oneOptions)
      ysValue.value = arr
    }
  }
  await changeCompany()
}
const changeCompany = async () => {
  const yv = ysValue.value.length ? ysValue.value[ysValue.value.length - 1] : ''
  const chatData = await api.kyRequest(yv)
  const result = chatData.data?.data
  if (isSuccess(chatData) && result?.length) {
    const data = result[0]
    const month = Number(moment(data.currentMonth).format('MM'))
    const ysLineX = [`${month}月实际归集金额`, `1-${month}月实际归集金额`, '年度总预算']
    const ysLineY = [Number(data.monthAmount), Number(data.totalAmount), Number(data.budgetAmount)]
    if (ysChat) ysChat.dispose()
    ysChat = echarts.init(ysEl.value)
    ysChat.setOption({
      tooltip,
      grid: {
        top: '80',
        left: '10',
        right: '2',
        bottom: '10',
        containLabel: true,
      },
      xAxis: {
        ...xAxis(ysLineX, true),
        axisLine: {
          show: false,
          lineStyle: {
            color: '#283460',
          },
        },
        axisLabel: {
          fontSize: 12,
          // interval: '0',
          color: '#FFFFFF',
        },
        //   axisLabel: {
        //   rotate: props.rotate,
        // },
        type: 'category',
        splitLine: {
          lineStyle: {
            color: 'rgba(131,101,101,0.2)',
            type: 'dashed',
          },
        },
      },
      yAxis: {
        ...yAxis(false),
        axisLine: {
          show: false,
        },
        axisPointer: {
          type: 'shadow',
        },
        axisLabel: {
          fontSize: 12,
          color: '#FFFFFF',
        },
        name: '单位 万元',
        // nameLocation: 'end',
        type: 'value',
        data: ysLineX,
        splitLine: {
          lineStyle: {
            color: 'rgba(131,101,101,0.2)',
            type: 'dashed',
          },
        },
      },
      series: {
        barWidth: fontSizeRem(0.3),
        ...series(ysLineY, '', '科研预算', '万元'),
        label: {
          show: true,
          position: 'top',
          color: '#fff',
        },
        itemStyle: {
          // color: '#C7A746',
          color: function (params) {
            //展示正值的柱子，负数设为透明
            let colorArr = params.value > 0 ? ['#C7A746', '#08103B'] : ['#08103B', '#C7A746']
            return new echarts.graphic.LinearGradient(
              0,
              0,
              0,
              1,
              [
                {
                  offset: 0,
                  color: colorArr[0], // 0% 处的颜色
                },
                {
                  offset: 1,
                  color: colorArr[1], // 100% 处的颜色
                },
              ],
              false
            )
          },
          barBorderRadius: [30, 30, 0, 0],
        },
      },
    })
  } else if (ysChat) ysChat.dispose()
}
// 科技实力
const slValue = ref<string>(moment().format('YYYY'))
let slChat: ECharts
const slLineX = ref<string[]>([])
const slLineY = ref<number[]>([])
const initSlChat = () => {
  api.slRequest(slValue.value).then((res) => {
    if (isSuccess(res)) {
      let data = res.data.data || []
      data = data.filter((t) => t.type)
      slLineX.value = data.map((t) => t.type) || []
      slLineY.value = data.map((t) => t.num) || []
    } else {
      slLineX.value = []
      slLineY.value = []
    }
  })
}
// 项目进展
const jzValue = ref<string>(moment().format('YYYY'))
let jzChat: ECharts
const jzLineX = ref<string[]>([])
const jzLineY = ref<number[]>([])
const initJzChat = () => {
  api.jzRequest(jzValue.value).then((res) => {
    if (isSuccess(res)) {
      let data = res.data.data || []
      data = data.filter((t) => t.type)
      jzLineX.value = data.map((t) => t.type) || []
      jzLineY.value = data.map((t) => t.num) || []
    } else {
      jzLineX.value = []
      jzLineY.value = []
    }
  })
}
// 数字化预算
const szValue = ref<string>(moment().format('YYYY'))
const szEl = ref<HTMLDivElement>()
let szChat: ECharts
const initSzChat = () => {
  api.szRequest(szValue.value).then((res) => {
    if (isSuccess(res)) {
      let data = res.data.data || []
      data = data.filter((t) => t.belongingUnit)
      const szLineX = data.map((t) => t.belongingUnit) || []
      const szLineY =
        data.map((t) => {
          console.log(t.budgetAmount, 't.budgetAmount')
          return t.budgetAmount.toFixed(2)
        }) || []
      if (szChat) szChat.dispose()
      szChat = echarts.init(szEl.value)
      szChat.setOption({
        tooltip,
        grid: {
          top: '80',
          left: '0',
          right: '2',
          bottom: '0',
          containLabel: true,
        },
        color: ['#6B305A'],
        legend: {
          textStyle: {
            color: '#fff',
          },
          itemWidth: 14,
          top: '50',
          right: '10%',
        },
        xAxis: {
          axisPointer: {
            type: 'shadow',
          },
          ...xAxis(szLineX, true, szLineX.length),
          axisLine: {
            show: false,
            lineStyle: {
              color: '#6B305A',
            },
          },
          axisLabel: {
            // interval: '0',
            rotate: 30,
            formatter: function (value) {
              // 如果标签长度大于10，截断并添加省略号
              return value.length > 5 ? value.slice(0, 5) + '...' : value;
            },
            color:'#24336C'
          },
          splitLine: {
            lineStyle: {
              color: 'rgba(131,101,101,0.2)',
              type: 'dashed',
            },
          },
        },
        yAxis: {
          ...yAxis(true),
          name: '单位 万元',
          axisLine: {
            show: false,
            lineStyle: {
              color: '#bfc0c5',
            },
          },
          splitLine: {
            lineStyle: {
              color: 'rgba(131,101,101,0.2)',
              type: 'dashed',
            },
          },
        },
        series: {
          barWidth: fontSizeRem(0.3),
          ...series(szLineY, '#0272FC', '预算', '万元'),
          label: {
            show: true,
            position: 'top',
            color: '#fff',
          },
          itemStyle: {
            // color: '#C7A746',
            color: function (params) {
              //展示正值的柱子，负数设为透明
              let colorArr = params.value > 0 ? ['#6B305A', '#08103B'] : ['#08103B', '#6B305A']
              return new echarts.graphic.LinearGradient(
                0,
                0,
                0,
                1,
                [
                  {
                    offset: 0,
                    color: colorArr[0], // 0% 处的颜色
                  },
                  {
                    offset: 1,
                    color: colorArr[1], // 100% 处的颜色
                  },
                ],
                false
              )
            },
            barBorderRadius: [30, 30, 0, 0],
          },
        },
        // [series(szLineY, '#0272FC', '预算', '万元')],
      })
    } else if (szChat) szChat.dispose()
  })
}
// 专家与人才
let rcChat: ECharts
const rcLineX = ref<string[]>(['中咨专家数', '上报中交数', '中咨人才数', '上报中交专家数'])
const rcLineY = ref<number[]>([])
const initRcChat = () => {
  api.rcRequest().then((res) => {
    const result = res?.data?.data
    if (isSuccess(res) && result.length) {
      const data = result[0]
      rcLineY.value = [data.num1, data.num2, data.num3, data.num4]
    } else rcLineY.value = []
  })
}
const changeChat = (chat: ECharts, type: string) => {
  if (type === 'glChat') glChat = chat
  if (type === 'slChat') slChat = chat
  if (type === 'jzChat') jzChat = chat
  if (type === 'szChat') szChat = chat
  if (type === 'rcChat') rcChat = chat
}
const windowEvent = () => {
  windowResize(300, () => {
    if (glChat) glChat.resize()
    if (ysChat) ysChat.resize()
    if (slChat) slChat.resize()
    if (jzChat) jzChat.resize()
    if (szChat) szChat.resize()
    if (rcChat) rcChat.resize()
  })
}
onMounted(() => {
  initGlChat()
  initSlChat()
  initJzChat()
  initYsChat()
  initSzChat()
  initRcChat()
  window.addEventListener('resize', () => {
    windowEvent()
  })
})
onUnmounted(() => {
  window.removeEventListener('resize', windowEvent)
})
</script>

<template>
  <div class="chartContent">
    <div class="row mb10">
      <div class="modal modal1-6">
        <span class="title">考核管理</span>
        <span class="rank modalTitle">贡献度排行</span>
        <chat
          :line-x="glLineX"
          :line-y="glLineY"
          description="考核管理"
          :split-line="true"
          :slider="false"
          :randomColor="false"
          rotate="30"
          color="#0291D1"
          :changeChat="changeChat"
          type="glChat"
          unit=""
        ></chat>
      </div>
    </div>
    <div class="row">
      <div class="modal modal1-3">
        <!--    <el-select-->
        <!--      v-model="ysValue"-->
        <!--      class="m-2 searchItem searchRight"-->
        <!--      placeholder="请选择"-->
        <!--      @change="changeCompany"-->
        <!--    >-->
        <!--      <el-option-->
        <!--        v-for="item in ysOptions"-->
        <!--        :key="item.id"-->
        <!--        :label="item.name"-->
        <!--        :value="item.id"-->
        <!--      />-->
        <!--    </el-select>-->
        <div class="m-2 searchItem searchRight">
          <el-cascader
            popper-class="custom-cascader"
            v-model="ysValue"
            clearable
            :options="ysOptions"
            :props="{ value: 'id', label: 'name' }"
            @change="changeCompany"
          />
        </div>
        <span class="title">科研预算</span>
        <div ref="ysEl" class="chat"></div>
      </div>
      <div class="modal modal1-3">
        <div class="searchItem searchRight">
          <el-date-picker
            v-model="slValue"
            type="year"
            placeholder="请选择"
            value-format="YYYY"
            format="YYYY"
            clearable
            @change="initSlChat"
          />
        </div>
        <span class="title">科技实力</span>
        <chat
          :line-x="slLineX"
          :line-y="slLineY"
          description="科技实力"
          :split-line="true"
          color="#A571E0"
          :changeChat="changeChat"
          type="slChat"
          unit=""
        ></chat>
      </div>
    </div>
    <div class="row">
      <div class="modal">
        <div class="searchItem searchRight">
          <el-date-picker
            v-model="jzValue"
            type="year"
            placeholder="请选择"
            value-format="YYYY"
            format="YYYY"
            clearable
            @change="initJzChat"
          />
        </div>
        <span class="title">项目进展</span>
        <chat
          :line-x="jzLineX"
          :line-y="jzLineY"
          description="项目进展"
          :split-line="true"
          color="#519BBD"
          :random-color="false"
          :changeChat="changeChat"
          type="jzChat"
          unit=""
        ></chat>
      </div>
      <div class="modal">
        <div class="searchItem searchRight">
          <el-date-picker
            v-model="szValue"
            type="year"
            placeholder="请选择"
            value-format="YYYY"
            format="YYYY"
            clearable
            @change="initSzChat"
          />
        </div>
        <span class="title">数字化预算</span>
        <div ref="szEl" class="chat"></div>
      </div>
      <div class="modal">
        <span class="title">专家与人才</span>
        <chat
          :line-x="rcLineX"
          :line-y="rcLineY"
          description="科技实力"
          :split-line="true"
          color="#4DBB94"
          :changeChat="changeChat"
          type="rcChat"
          unit=""
        ></chat>
      </div>
    </div>
  </div>
</template>

<style scoped lang="scss">
// @import "@/assets/css/theme";
@import '../common';
.chartContent {
  height: 150% !important;
  overflow-y: scroll;
  flex-direction: column;
  .row,
  .modal {
    display: flex;
    flex: 1 1 0;
    overflow: hidden;
  }
  .modal1-6 {
    background-image: url(../img/echars-bg1-6.png) !important;
  }
  .modal1-3 {
    background-image: url(../img/echars-bg1-3.png) !important;
  }
  .modal {
    position: relative;
    margin-right: 10px;
    padding: 2vh;
    padding-top: 3vh;
    &:last-child {
      margin-right: 0;
    }
    background-image: url(../img/echars-bg.png);
    background-size: 100% 100%;
    .title {
      position: absolute;
      top: 3vh;
      flex: 0;
      color: aliceblue;
    }
    .searchRight {
      top: 3vh;
      right: 2vh;
    }
    .rank {
      position: absolute;
      top: 3vh;
      left: 80%;
      right: 0 !important;
    }
    :deep(.el-input--small .el-input__inner) {
      border: none;
      color: aliceblue;
      background-color: #192e6e !important;
    }
  }
}
</style>
